package cn.fan.web;

import cn.fan.constants.DataBaseConstants;
import cn.fan.pojo.User;
import cn.fan.service.UserService;
import cn.fan.utils.MyPage;
import cn.fan.utils.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("test")
    public String test(){
        return "hello,test!!";
    }

    @GetMapping("sysUser")
    public User sysUser(){
        return userService.getSysUser();
    }

    @GetMapping("sysUserId")
    public long sysUserId(){
        return userService.getSysUserId();
    }

    @PostMapping("login")
    public R login(@RequestBody User user){
        try {
            return userService.login(user);
        } catch (Exception e) {
            return R.error("未知异常！");
        }
    }

    @GetMapping("logout")
    public R logout(){
        userService.logout();
        return R.ok();
    }

    @PostMapping("add")
    public R add(@RequestBody User user){
        int i = userService.add(user);
        Map<String,Object> res = new HashMap<>();
        res.put("user",user);
        return i> DataBaseConstants.NO_DATA ? R.ok(res) : R.error("添加失败,或当前操作用户登录超时");
    }

    @GetMapping("delete/{id}")
    public R delete(@PathVariable("id") Long id){
        int i = userService.delete(id);
        return i> DataBaseConstants.NO_DATA ? R.ok() : R.error("无该用户,或当前操作用户登录超时");
    }

    @PostMapping("edit")
    public R edit(@RequestBody User user){
        int i = userService.edit(user);
        return i> DataBaseConstants.NO_DATA ? R.ok() : R.error("无该用户,或当前操作用户登录超时");
    }

    @GetMapping("get/{id}")
    public R get(@PathVariable("id") long id){
        User user = userService.getByIdNoPswd(id);
        if(null == user)
            return R.error("无该用户");

        Map<String,Object> res = new HashMap<>();
        res.put("user",user);
        return R.ok(res);
    }

    @PostMapping("list")
    public R list(@RequestBody Map<String,Object> map){
        List<User> list = userService.list(map);
        Map<String,Object> res = new HashMap<>();
        res.put("list",list);
        return R.ok(res);
    }

    // 需要加点东西，额外添加一个类，来封装page信息，
    //      当前页，总页数，是否第一页，是否最后一页，相邻的几页

    @PostMapping("list/{pageSize}/{currentPage}")
    public R page(@RequestBody Map<String,Object> map,@PathVariable("pageSize") long pageSize,@PathVariable("currentPage") long currentPage){
        IPage<User> page = userService.page(map,currentPage,pageSize);
        MyPage pagination=new MyPage(page);
        Map<String,Object> res = new HashMap<>();
//        res.put("page",page);
        res.put("pagination",pagination);
        return R.ok(res);
    }

}
